﻿using System;
using Infrastructure;
using Microsoft.AspNetCore.Mvc;
using OpenAuth.App;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository.Domain;

namespace OpenAuth.WebApi.Controllers
{
    /// <summary>
    /// InspectStandard操作
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class InspectStandardsController : ControllerBase
    {
        private readonly InspectStandardApp _app;

        //获取详情
        [HttpGet]
        public Response<InspectStandard> Get(string id)
        {
            var result = new Response<InspectStandard>();
            try
            {
                result.Result = _app.GetOne(id);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }

        //添加
        [HttpPost]
        public Response Add(InspectStandard obj)
        {
            var result = new Response();
            try
            {
                _app.Add(obj);

            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }

        //修改
        [HttpPost]
        public Response Update(InspectStandard obj)
        {
            var result = new Response();
            try
            {
                if (obj.Items == null || obj.Items.Count == 0)
                {
                    throw new Exception("检查项不能为空！");
                }
                foreach (var item in obj.Items)
                {
                    if (item.Max == null && item.Min == null && item.AlarmMode == 1)
                        throw new Exception("报警方式为参考界限时，最小值和最大值不能都为空！");
                }
                _app.Update(obj);

            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 加载列表
        /// </summary>
        [HttpGet]
        public TableData Load([FromQuery]QueryInspectStandardListReq request)
        {
            return _app.Load(request);
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        [HttpPost]
        public Response Delete([FromBody]string[] ids)
        {
            var result = new Response();
            try
            {
                _app.Delete(ids);

            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return result;
        }

        public InspectStandardsController(InspectStandardApp app)
        {
            _app = app;
        }
    }
}
